package com.leolian.code.fragment.book.concurrence.chapter06;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.leolian.code.fragment.book.concurrence.chapter05.Preloader;

public class FutureRenderer {
	private final ExecutorService exec = Executors.newFixedThreadPool(8);

	public void renderPage(CharSequence source) {
		final List<ImageInfo> imageInfos = scanForImageInfo(source);
		Callable<List<ImageData>> task = new Callable<List<ImageData>>() {
			public List<ImageData> call() {
				List<ImageData> result = new ArrayList<ImageData>();
				for (ImageInfo imageInfo : imageInfos) {
					result.add(imageInfo.downloadImage());
				}
				return result;
			}
		};

		Future<List<ImageData>> future = exec.submit(task);
		renderText(source);

		try {
			List<ImageData> imageData = future.get();
			for (ImageData data : imageData) {
				renderImage(data);
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			future.cancel(true);
		} catch (ExecutionException e) {
			throw Preloader.launderThrowable(e.getCause());
		}

	}

	/**
	 * @param source
	 */
	private void renderText(CharSequence source) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @param data
	 */
	private void renderImage(ImageData data) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @param source
	 * @return
	 */
	private List<ImageInfo> scanForImageInfo(CharSequence source) {
		// TODO Auto-generated method stub
		return null;
	}

}
class ImageData {
	
}
class ImageInfo {

	/**
	 * @return
	 */
	public ImageData downloadImage() {
		// TODO Auto-generated method stub
		return null;
	}
	
}